package org.Image.management.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;

@Slf4j
public class FileDeletionService {
    public static void deleteFileWithRetryButThread(Path filePath, int maxRetries, long retryIntervalMillis) {
        new Thread(() -> new FileDeletionService().deleteFileWithRetry(filePath, maxRetries, retryIntervalMillis)).start();
    }

    public void deleteFileWithRetry(Path filePath, int maxRetries, long retryIntervalMillis) {
        for (int attempt = 0; attempt < maxRetries; attempt++) {
            try {
                if (!Files.exists(filePath)) {
                    log.info("文件不存在，无需删除: {}", filePath);
                    return;
                }
                Files.delete(filePath);
                log.info("文件删除成功: {}", filePath);
                return;
            } catch (IOException e) {
                if (attempt == maxRetries - 1) {
                    log.error("文件删除失败，超过最大重试次数:{} ", filePath);
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(retryIntervalMillis);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    log.error("删除文件时线程中断{}", ie.getMessage());
                }
            }
        }
    }
}
